//
//  PHMineViewController.m
//  SecondLoan
//
//  Created by Echo Zhangjie on 2019/8/22.
//  Copyright © 2019 姚永波. All rights reserved.
//

#import "PHMineViewController.h"
#import "PHMineTableViewCell.h"
#import "PHMineHeaderView.h"
#import "LoginController.h"
#import "SLBorrowRecordController.h"
#import "SLLoanApplyViewController.h"
#import "PDWebViewController.h"
#import "SLAmountViewController.h"
#import "SLSettingViewController.h"
#import "SLEditInfoViewController.h"
#import "SLMyInfoManagerVC.h"
#import "IDCardViewController.h"
#import "UserMineInfo.h"
#import "MyMoneyRangeModel.h"
#import "SLVerifySubmitViewController.h"
#import "SLVerifyFailedViewController.h"
#import "SLProductInfoViewController.h"
#import "WKBGlobalData.h"
#import "YSHYClipViewController.h"
#import "UIImage+Stretch.h"

@interface PHMineViewController () <UITableViewDelegate, UITableViewDataSource, PHMineHeaderViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *rowDataArray;
@property (strong, nonatomic) PHMineHeaderView *headerView;
@property (strong, nonatomic) UserMineInfo *mineModel;
@property (strong, nonatomic) MyMoneyRangeModel *myMoneyRange;
@property (nonatomic, assign) BOOL isAuth;
@end

@implementation PHMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.rowDataArray = [NSMutableArray arrayWithObjects:@[@"mine_jiekuan",@"借款记录"],
                                              @[@"mine_jilu",@"申请记录"],
                                              @[@"mine_edu",@"我的额度"],
                                              @[@"mine_guanli",@"基础信息管理"],
                                              nil];
    [self setDefaultTopView];
}
- (void)setDefaultTopView{
    if ([WKBGlobalData shareManager].mineInfo) {
        self.mineModel = [WKBGlobalData shareManager].mineInfo;
        if (self.mineModel) {
            self.headerView.mineModel = self.mineModel;
        }else{
            [self.headerView setDefaultLogin];
        }
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    self.myMoneyRange = nil; // 退出登录的时候该值应该清空
    [self.view sendSubviewToBack:self.navigationBarBgView];
    [self configView];
}
- (void)configView{
    if ([UserLocal isLogin]) {
        if (self.mineModel){
        }else{
            [self.headerView setDefaultLogin];
        }
        NSMutableDictionary * param = [NSMutableDictionary dictionary];
        [param setObject:[UserLocal token] forKey:@"token"];
        [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_user_home_info) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
            [self HUDdismiss];
            if (!error) {
                self.mineModel = [UserMineInfo mj_objectWithKeyValues:responseObject[@"data"]];
                [WKBGlobalData shareManager].mineInfo = self.mineModel;
                if (self.mineModel) {
                    self.headerView.mineModel = self.mineModel;
                }else{
                    [self.headerView setDefaultLogin];
                }
            } else {
                [self HUDshowErrorWithStatus:error.localizedDescription];
            }
            [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_get_auth) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
                [self HUDdismiss];
                if (!error) {
                    BOOL isAuth = NO;
                    if ([responseObject[@"data"] integerValue] == CodeVerifyPassed){
                        isAuth = YES;
                    }
                    self.isAuth = isAuth;
                    [self.headerView setAuthStatus:isAuth];
                } else {
                    [self HUDshowErrorWithStatus:error.localizedDescription];
                }
            }];
        }];
        [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_my_quota) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
            [self HUDdismiss];
            if (!error) {
                self.myMoneyRange = [MyMoneyRangeModel mj_objectWithKeyValues:responseObject[@"data"]];
            }
        }];
    }else{
        [self.headerView setDefault];
    }
}
#pragma mark ==== UITableView ======
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc]initWithFrame:CGRectMake( 0, 0,self.view.frame.size.width, 0.01)];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]initWithFrame:CGRectMake( 0, 0,self.view.frame.size.width, 0.01)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return 54;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  PHMineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PHMineTableViewCell" forIndexPath:indexPath];
  [cell bindData:self.rowDataArray[indexPath.row][0] title:self.rowDataArray[indexPath.row][1]];
  return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return self.rowDataArray.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) { //借款记录
        [self borrowClick];
    }else if (indexPath.row == 1){//贷款申请记录
        [self loanClick];
    }else if (indexPath.row == 2){//我的额度
        if (![UserLocal isLogin]) {
            MainNavigationController * vc = [[MainNavigationController alloc]initWithRootViewController:[LoginController new]];
            [self presentViewController:vc animated:YES completion:nil];
        }else{
            [self goMyAmout];
        }
    }else if (indexPath.row == 3){ //基础信息管理
        [self editClick];
    }else if (indexPath.row == 4){ //设置
        if (![UserLocal isLogin]) {
            MainNavigationController * vc = [[MainNavigationController alloc]initWithRootViewController:[LoginController new]];
            [self presentViewController:vc animated:YES completion:nil];
        }else{
            SLSettingViewController *settingVC = [[SLSettingViewController alloc] init];
            settingVC.mineModel = self.mineModel;
            [self.navigationController pushViewController:settingVC animated:YES];
        }
    }else if (indexPath.row == 5){ //联系我们
        PDWebViewController * vc = [[PDWebViewController alloc] init];
        vc.webUrl = url_contect_us;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)goMyAmout{
    SLAmountViewController *AmountVC = [[SLAmountViewController alloc] init];
    [self.navigationController pushViewController:AmountVC animated:YES];    
}

# pragma mark ====== click ========
- (void)loanClick
{
    if (![UserLocal isLogin]) {
        MainNavigationController * vc = [[MainNavigationController alloc]initWithRootViewController:[[LoginController alloc] init]];
        [self presentViewController:vc animated:YES completion:nil];
    }else{
        SLLoanApplyViewController * vip = [[SLLoanApplyViewController alloc] init];
        [self.navigationController pushViewController:vip animated:YES];
    }
}

- (void)borrowClick
{
    if (![UserLocal isLogin]) {
        MainNavigationController * vc = [[MainNavigationController alloc]initWithRootViewController:[[LoginController alloc] init]];
        [self presentViewController:vc animated:YES completion:nil];
    }else{
        SLBorrowRecordController *finishVC = [[SLBorrowRecordController alloc] init];
        [self.navigationController pushViewController:finishVC animated:YES];
    }
}

- (void)editClick
{
    if (![UserLocal isLogin]) {
        MainNavigationController * vc = [[MainNavigationController alloc]initWithRootViewController:[LoginController new]];
        [self presentViewController:vc animated:YES completion:nil];
    }else{
        SLMyInfoManagerVC *editVC = [[SLMyInfoManagerVC alloc] init];
        [self.navigationController pushViewController:editVC animated:YES];
    }
}

    // MARK: PHMineHeaderViewDelegate
- (void)apply {
#warning test
        if(self.myMoneyRange.status == CodeCreditDoing){
            SLVerifySubmitViewController *doingVC = [[SLVerifySubmitViewController alloc] initWithNibName:@"SLVerifySubmitViewController" bundle:nil];
            doingVC.isPuhui = YES;
            [self.navigationController pushViewController:doingVC animated:YES];
        }else if (self.myMoneyRange.status == CodeCreditNotPassed){
            SLVerifyFailedViewController *failedVC = [[SLVerifyFailedViewController alloc] initWithNibName:@"SLVerifyFailedViewController" bundle:nil];
            [self.navigationController pushViewController:failedVC animated:YES];
        }else{
            SLProductInfoViewController *productInfo = [[SLProductInfoViewController alloc] init];
            productInfo.productId = [WKBGlobalData shareManager].productIdPuhui;
            productInfo.isPuhui = YES;
            [self.navigationController pushViewController:productInfo animated:YES];
        }
}

- (void)login {
  MainNavigationController * vc = [[MainNavigationController alloc]initWithRootViewController:[LoginController new]];
  [self presentViewController:vc animated:YES completion:nil];
}

- (void)showPersonalInfo {
    // 如果未认证去去认证
    debugLog(@"go card verify");
    if (!self.isAuth) {
        IDCardViewController *cardVC = [[IDCardViewController alloc] initWithNibName:@"IDCardViewController" bundle:nil];
        cardVC.isOnlyAuth = YES;
        [self.navigationController pushViewController:cardVC animated:YES];
    }
}
- (void)goSetting{
    if (![UserLocal isLogin]) {
        MainNavigationController * vc = [[MainNavigationController alloc]initWithRootViewController:[LoginController new]];
        [self presentViewController:vc animated:YES completion:nil];
    }else{
        SLSettingViewController *settingVC = [[SLSettingViewController alloc] init];
        settingVC.mineModel = self.mineModel;
        [self.navigationController pushViewController:settingVC animated:YES];
#pragma mark test
//        SLEditInfoViewController *editVC = [[SLEditInfoViewController alloc] init];
//        [self.navigationController pushViewController:editVC animated:YES];
    }
}
- (void)goSetAvatar{
    if (![UserLocal isLogin]) {
        MainNavigationController * vc = [[MainNavigationController alloc]initWithRootViewController:[LoginController new]];
        [self presentViewController:vc animated:YES completion:nil];
    }else{
//        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照上传",@"本地上传", nil];
//        [sheet showInView: self.view];
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
        UIImagePickerController *pickController = [[UIImagePickerController alloc] init];
        pickController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        pickController.delegate = self;
        pickController.allowsEditing = YES;
        if ([pickController.navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
            [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:COLOR_ThemeRed,
                                                                   NSFontAttributeName:[UIFont systemFontOfSize:18]}];
            [[UINavigationBar appearance] setTranslucent:NO];
            [[UINavigationBar appearance] setTintColor:COLOR_ThemeRed];
        }
        [self presentViewController:pickController animated:YES completion:nil];
    }
}

- (void)logoTapped {
    PDWebViewController * vc = [[PDWebViewController alloc] init];
    vc.webUrl =  url_about_us;
    vc.isAboutUS = YES;
    [self.navigationController pushViewController:vc animated: YES];
}


#pragma mark UIActionSheetDelegate
//- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    switch (buttonIndex) {
//        case 0:
//        {
//            UIImagePickerController *pickController = [[UIImagePickerController alloc] init];
//            pickController.delegate = self;
//            pickController.sourceType = UIImagePickerControllerSourceTypeCamera;
//            pickController.allowsEditing = YES;
//            [self presentViewController:pickController animated:YES completion:nil];
//        }
//            break;
//        case 1:
//        {
//            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
//            UIImagePickerController *pickController = [[UIImagePickerController alloc] init];
//            pickController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//            pickController.delegate = self;
//            pickController.allowsEditing = YES;
//            if ([pickController.navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
//                [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:COLOR_ThemeRed,
//                                                                       NSFontAttributeName:[UIFont systemFontOfSize:18]}];
//                [[UINavigationBar appearance] setTranslucent:NO];
//                [[UINavigationBar appearance] setTintColor:COLOR_ThemeRed];
//            }
//            [self presentViewController:pickController animated:YES completion:nil];
//        }
//            break;
//    }
//}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],
                                                           NSFontAttributeName:[UIFont systemFontOfSize:18]}];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],
                                                           NSFontAttributeName:[UIFont systemFontOfSize:18]}];
    UIImage *image = info[UIImagePickerControllerEditedImage];
    [self ClipViewController:nil FinishClipImage:image];
}

#pragma mark - ClipViewControllerDelegate
-(void)ClipViewController:(YSHYClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage {
    UIImage *image = editImage;
    CGFloat expectWidth  = 0.;
    CGFloat expectHeight = 0;
    if (image.size.width > image.size.height) {
        expectWidth = 800;
        CGFloat imageWidth  = image.size.width;
        expectHeight= expectWidth / imageWidth * image.size.height;
    }else{
        expectHeight = 800;
        CGFloat imageHeight  = image.size.height;
        expectWidth = expectHeight / imageHeight * image.size.width;
    }
    CGSize expectSize = CGSizeMake(expectWidth, expectHeight);
    UIImage *resizeImage = [image scaleToSize:expectSize];
    //    NSData *imageData = UIImageJPEGRepresentation(image, .8);
    NSData *imageData = UIImageJPEGRepresentation(resizeImage, .8);
    if (image) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.label.text = @"上传中";
        NSMutableDictionary * param = [NSMutableDictionary dictionary];
        [param setObject:[UserLocal token] forKey:@"token"];
        NSString *encodedData= [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        [param setObject:encodedData forKey:@"file"];
        [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(usl_upload_face) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
//            [hud hideAnimated:YES];
            if (!error) {
                NSMutableDictionary * param = [NSMutableDictionary dictionary];
                [param setObject:[UserLocal token] forKey:@"token"];
                [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_user_home_info) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
                    if (!error) {
                        self.mineModel = [UserMineInfo mj_objectWithKeyValues:responseObject[@"data"]];
                        [WKBGlobalData shareManager].mineInfo = self.mineModel;
                        if (self.mineModel) {
                            self.headerView.mineModel = self.mineModel;
                        }else{
                            [self.headerView setDefaultLogin];
                        }
                    } else {
                        [self HUDshowErrorWithStatus:error.localizedDescription];
                    }
                }];
            }
        }];
        [self dismissViewControllerAnimated:YES completion:^{
            [hud hideAnimated:YES afterDelay:2];
        }];
    }
}
#pragma mark ======= set,get =====
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.frame = CGRectMake(0, KStatusBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT - KStatusBarHeight);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.bounces = NO;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _tableView.tableHeaderView = self.headerView;
        [_tableView registerNib:[UINib nibWithNibName:@"PHMineTableViewCell" bundle:nil] forCellReuseIdentifier:@"PHMineTableViewCell"];
    }
    return _tableView;
}
- (PHMineHeaderView *)headerView{
    if (!_headerView) {
        _headerView = [PHMineHeaderView newView];
        _headerView.frame = CGRectMake(0, 0, _tableView.width, 370);
        _headerView.delegate = self;
    }
    return _headerView;
}
@end
